<script type="text/javascript">
//Redirect to the correct page URL if we have session storage variables in cache.
          function getURLVariable(variable){
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
                   return(false);
        }
                
     		function checkURLelements(variable){            
               if(getURLVariable(variable)==sessionStorage[variable]){   
			   	//do nothing because we are on the correct URL
			   }else{
					//refresh page with correct URL
					if(getURLVariable(variable)=="undefined"){
						
						if(sessionStorage[variable]=="undefined"){
							window.location.href = "chartDifShares.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate'];
						}
					}else{
							window.location.href = "chartDifShares.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate'];
					}
					
			   }
			}
			
			//check all of the possible session Storage elements
			checkURLelements("symbols");checkURLelements("type");checkURLelements("percentage");checkURLelements("endDate");checkURLelements("startDate");
			
				
</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
session_start();
require_once("../Scripts/DatabaseConnect.php");
require_once("../Scripts/UpdateStocks.php");//Checks if we need to update the database with new market data.

//Check if we need local server or remote server
$con=Remoteconnect();
if($con==null){
	$con=Localconnect();	
}
//Display the last update date and current date and time.
$lastUpdate="";
$result = mysqli_query($con,"SELECT * FROM  `time`");

while($row = mysqli_fetch_array($result)) {
	$lastUpdate=$row['LastUpdate'];

  
}

$date = date('m-d-Y h:i:s a', time());//gets current date and time of server.
echo"Date: $date, Last Update: $lastUpdate";
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN" dir="ltr">
<head profile="http://gmpg.org/xfn/11">
<title>J&J Free Stock backtesting</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="imagetoolbar" content="no" />
<link rel="stylesheet" href="businesstoday/styles/layout.css" type="text/css" />
</head>
<body id="top">
<div class="wrapper col1">
  <div id="header">
    <img src="../Images/the-top-5-high-volume-trading-stocks-of-the-week_1118_437849_0_14042581_500.jpg" alt="" width="240" height="162" />
    <div id="logo">
      <h1>J&amp;J Free Stock Backtesting    </h1>
    </div>
    <div id="newsletter">
    <div id="login" style="display:block; min-height:50px; min-width:600px;">
      <p><a href="#">Lost your password?</a> <a href="register.php">Register</a>

      </p>
      
      <form action="../Scripts/authenticate.php" method="post" >
      
        <fieldset>
          <legend>NewsLetter</legend>
          <table>
            <tr>
              <td>Name:</td>
              <td><input type="email" name="email" required id="email" /></td>
              <td>Password:</td>
              <td><input type="password" name="password" required id="password" /></td>
              <td><input type="submit" name="news_go" id="news_go" value="Login" /></td>
            </tr>
          </table>
        </fieldset>
      </form>


      </div>
      
      <?php
	  //Wrong password message
      if (isset($_SESSION['msg'])) {
	echo "<p style='color:red'>".$_SESSION['msg']."</p>"; 
	//remove the message since it has been displayed.
	unset($_SESSION['msg']);
	}
	?>
    
   	<?php
	//logout button
    if (isset($_SESSION['msgG'])) {
		echo"<form>";
		echo "<p style='color:green'>".$_SESSION['msgG']."</p>"; 
		echo '<input type="button" name="logout" id="logout" value="Logout" onClick="location.href=\'../Scripts/Logout.php\'"/>'; 
		echo"</form>";
	}
	
?> 
  

    </div>
    <br class="clear" />
  </div>
</div>

<div class="wrapper col2">
  <div id="topbar">
    <div id="topnav">
      <ul>
        <li class="active">
         
              <li><a href="index.php">Home Page</a></li>
              <li id="portfolio" style="display:none"><a href="portfolio.php">Stock Portfolio</a></li>
              <li id="stockMonitoring" style="display:none"><a href="stockMonitoring.php">Stock Monitoring</a></li>
              <li><a href="stockbacktest.php">Stock Backtest</a></li>
              <li><a href="charts.php">Stock Charts</a>
               <ul>
            <li><a href="chartDifShares.php">Stock Prices Comparision Chart</a></li>
            <li><a href="chartIndicators.php">Stock Technical Analysis Chart</a></li>
         
          </ul>
        </li>

        
  </li>      
        
        
      </ul>
    </div>
 <script type="text/javascript">
 //Hides/Shows navigation bar links based on logged in status
	  var check = <?php echo json_encode(isset($_SESSION['email'])); ?>;
	  
	  if(check==true){
		  document.getElementById("login").style.display="none";
		  document.getElementById("portfolio").style.display="block";
		  document.getElementById("stockMonitoring").style.display="block";

	  }else{
		  document.getElementById("login").style.display="block";
		  document.getElementById("stockMonitoring").style.display="none";
		  document.getElementById("portfolio").style.display="none";
		  
	  }
 </script>
 
       
    <br class="clear" />
  </div>
</div>
<div class="wrapper col3">  <div id="intro">
    

   
    <div class="fl_right"></div>
    <br class="clear" />
  </div>
</div>
<div class="wrapper col4"></div>
<div class="wrapper col5">
  <div id="container">

      
            
  <?php
	 require_once("../Scripts/chartProcess.php");//obtains data from database to draw the charts
  ?>
    
      <link rel="stylesheet" type="text/css" href="../Styles/style.css" />
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
                
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(ClosePriceDrawChart);
          google.setOnLoadCallback(VolumeDrawChart);

          //global variables
          var symbols =[];
          var startDate="";
          var endDate="";

function addSymbol(){           
                symbol=document.getElementById("comparestock");
                if(symbol.value!="none"){
                symbol=document.getElementById("comparestock");
                symbols.push(symbol.value);
                        //remove duplicate symbols
                        symbols = symbols.filter(function(elem, pos, self) {
                                return self.indexOf(elem) == pos;
                        })
                
                
                if(sessionStorage['symbols']){
                        var localsymbols=sessionStorage['symbols'].split(",");
                        for(i=0;i<localsymbols.length;i++){
                                symbols.push(localsymbols[i]);  
                        }
                        symbols = symbols.filter(function(elem, pos, self) {
                        return self.indexOf(elem) == pos;
                                })
                                
                        
                }
                
                window.sessionStorage.setItem("symbols", symbols);
                
                displaySymbols()
                }
                        
                //refresh page if we have either of the symbols
                if(sessionStorage['symbols']){            
        window.location.href = "chartDifShares.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate'];
                }
                
          }

function processPercentage(){
var percentage=document.getElementById("percentage");
 if(percentage.checked==true){
        window.sessionStorage.setItem("percentage","true");       
} 

if(percentage.checked==false){
        window.sessionStorage.setItem("percentage","false");      
}
        window.location.href = "chartDifShares.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate'];
}


function processType(){
var type= document.getElementById('Type');
if(type.value!="none"){
        if(sessionStorage["type"]){
                sessionStorage["type"]=type.value;        
        }
        else{
                window.sessionStorage.setItem("type",type.value); 
        }
}else{
        window.sessionStorage.setItem("type","Close");    
}
        window.location.href = "chartDifShares.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate'];

}

          
function processDate(){
                startDate=document.getElementById("startDate").value;
                endDate=document.getElementById("endDate").value;
                
                window.sessionStorage.setItem("startDate", startDate);
                window.sessionStorage.setItem("endDate", endDate);
                        
                //refresh page if we have the 
                if(sessionStorage['startDate']&&sessionStorage['endDate']){         
        window.location.href = "chartDifShares.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate'];
                }
                  
          }

          
function ClosePriceDrawChart() {//Close Price

                //ensure we have all of the required variables
                if(sessionStorage['startDate']&&sessionStorage['endDate']&&sessionStorage['symbols']&&sessionStorage['type']){
                //set value of dates from local storage.        
                document.getElementById("closePriceChart_div").style.display="block";//show the chart div
                
                  
  var time = <?php echo json_encode($dates); ?>;
  var Symboldata=<?php echo json_encode($symbolArray); ?>;;

  var data = new google.visualization.DataTable();
  data.addColumn('date', 'days');
  
        //add column for each symbol        
        var localsymbols=sessionStorage['symbols'].split(",");
        
        for( i=0; i< localsymbols.length;i++){
                data.addColumn('number',localsymbols[i]);       
                
        }
          
        //for the length of the Symbol data array
  
  for(i = 0; i < time.length; i++){
          
        //add row based on count of symbols
        var row=[];
        var index=0;
        
        var date= time[i].split("-");
        row.push(new Date(date[0], date[1]-1,date[2]));
        
        for(thing in localsymbols){
        row.push(Number(Symboldata[index][i]));
        index+=1;
        }
        
    data.addRow(row);
       
  }
                }
				
		//Formate the chart
        var Min=Math.min.apply(Math, Symboldata);
        var Max=Math.max.apply(Math, Symboldata);
        var options = {
          title: 'Compare Stock Close Prices',
          hAxis: {title: 'Day',  titleTextStyle: {color: '#333'}},
          vAxis: {title: 'End price', minValue: Min},
                  explorer: {axis:'both',
          maxZoomin:0.25,
          keepInBounds: true
                  }
        };
                
        var chart = new google.visualization.AreaChart(document.getElementById('closePriceChart_div'));
        chart.draw(data, options);
      
          }
  
function VolumeDrawChart() {//Volume
        
                //ensure we have all of the required variables
                if(sessionStorage['startDate']&&sessionStorage['endDate']&&sessionStorage['symbols']&&sessionStorage['type']){
                document.getElementById("volumeChart_div").style.display="block";//show the chart div
                
                  // Create and populate the data table.
          
  var time = <?php echo json_encode($dates); ?>;
  var volumeData=<?php echo json_encode($volumeArray); ?>;
 

  var data = new google.visualization.DataTable();
  data.addColumn('date', 'days');
  
        //add column for each symbol
        var localsymbols=sessionStorage['symbols'].split(",");

        for( i=0; i< localsymbols.length;i++){
                data.addColumn('number',localsymbols[i]);       
                
        } 
      //for the length of the Symbol data array   
  for(i = 0; i < time.length; i++){
          
        //add row based on count of symbols
        var row=[];
        var index=0;
        var date= time[i].split("-");
        row.push(new Date(date[0], date[1]-1,date[2]));
        
        
        for(thing in localsymbols){
        row.push(Number(volumeData[index][i]));
        index+=1;
        }
        
    data.addRow(row);

        
  }
                }
		//Format the chart
        var Min=Math.min.apply(Math, volumeData);
        var Max=Math.max.apply(Math, volumeData);
        var options = {
          title: 'Compare Stock Volume',
          hAxis: {title: 'Day',  titleTextStyle: {color: '#333'}},
          vAxis: {title: 'Volume', minValue: Min},
                  explorer: {axis:'both',
          maxZoomin:0.25,
          keepInBounds: true
        }
        };
                
        var chart = new google.visualization.AreaChart(document.getElementById('volumeChart_div'));
        chart.draw(data, options);
      
          }
          
</script>
     <h2>Compare Different stock prices between different symbols</h2>
    <label for="textfield2">Add Symbol:</label>
    <select id='comparestock' name='Symbol'>
                  <option value='none'>Choose symbols</option>
              <?php
                                $result = mysqli_query($con,"SELECT * FROM  `company info`");

                                while($row = mysqli_fetch_array($result)) {
                                        
                                echo "<option value='$row[Symbol]'>" . $row['Symbol'] . "</option>";

                                }
                                
                                echo "</select>";
                                //mysqli_close($con);
                          
                          //generate a button for each symbol to remove         

                          ?>
             
            <button onClick="addSymbol()">Add</button>
            <br/>
            <span id="holdSymbols">&nbsp;</span>
            <br/>
              <label>Start date</label>
              <input type="date" id="startDate" onChange="processDate()">
              <label>End date</label>
              <input type="date" id="endDate" onChange="processDate()">
              <label>Type</label>
              <select id='Type' name='Type' onChange="processType()">
              <option value='none'>Choose type</option>
              <option value='Close'>Close</option>
              <option value='High'>High</option>
              <option value='Low'>Low</option>
              <option value='Open'>Open</option>
              </select>
              <input type="checkbox" name="percentage" id="percentage" value="percentage" onChange="processPercentage()">Compare %
              <br>
             
            
    </form>

            <div id="closePriceChart_div" style="width: 900px; height: 250px; display:none;"></div><!--Close price Div-->
            <div id="volumeChart_div" style="width: 900px; height: 250px; display:none;"></div><!--Volume Div-->

            
            
            
            
            <script type="text/javascript">
                        function deleteSymbol(name){
                                //find the symbol to delete in local symbols
                                var localsymbols=sessionStorage['symbols'].split(",");
                                
                                //find index of symbol to be deleted
                                var index = localsymbols.indexOf(name);
                                //delete element at index
                                localsymbols.splice(index, 1);
                                
                                //reset local storage of symbols
                                window.sessionStorage.setItem("symbols", localsymbols);
                                if(sessionStorage['symbols']==""){
        window.location.href = "chartDifShares.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate'];
                                        
                                        
                                }else{
                                displaySymbols()
                                drawChart()
                                }
                                
                                
                                        
                        }
                        function displaySymbols(){
                                
                        if(sessionStorage['symbols']){
                                
                                //foreach symbol added create html button
                                
                                var localsymbols=sessionStorage['symbols'].split(",");
                                var holdSymbols = document.getElementById("holdSymbols");       
                                
                                while (holdSymbols.firstChild) {
                                        holdSymbols.removeChild(holdSymbols.firstChild);
                                }
                                                
                                for( i=0; i< localsymbols.length;i++){
                                var element = document.createElement("input");  
                                
                                element.setAttribute("type", "button");
                                element.setAttribute("value", "remove,"+localsymbols[i]);
                                element.setAttribute("name", localsymbols[i]);
                                element.setAttribute("onClick", "deleteSymbol(this.name)");
                                
                                    
                                console.log(element);
                                //Append the element in page (in span).
                                
                                holdSymbols.appendChild(element);
                                
                                }
                                
 
                        }  
                        }
                        displaySymbols()
                //display all the things!       

                if(sessionStorage['startDate']){
                        document.getElementById("startDate").setAttribute("value", sessionStorage['startDate']);
                        
                }
                if(sessionStorage['endDate']){
                        document.getElementById("endDate").setAttribute("value", sessionStorage['endDate']);
                }
                if(sessionStorage["type"]){
                        
                        var type=document.getElementById("Type");
                        type.value=sessionStorage["type"];        
                }
                
                if(sessionStorage["percentage"]){
                        if(sessionStorage["percentage"]=="true"){
                                document.getElementById("percentage").setAttribute("checked", true);
                        }
                }

                        </script>  

      
      
  </div>
    <br class="clear" />
  </div>
</div>
<div class="wrapper col6"></div>
<div class="wrapper col7">
  <div id="copyright">
    <p class="fl_left">Copyright &copy; 2011 - All Rights Reserved - <a href="#">Domain Name</a></p>
    <p class="fl_right">Template by <a href="http://www.os-templates.com/" title="Free Website Templates">OS Templates</a></p>
    <br class="clear" />
  </div>
</div>
</body>
</html>
